<template>
    <div class="responsive-bar-chart">
        <div ref="chart" :style="{ width: '100%', height: '100%' }"></div>
    </div>
</template>
  
<script>

export default {
    name: 'ResponsiveBarChart',
    props: {
        options: {
            type: Object,
            default: () => ({})
        },
        hasGeoroam: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            chartInstance: null
        };
    },
    watch: {
        options: {
            handler(newValue, oldValue) {
                this.updateChart();
            },
            // immediate: true,
            deep: true
        }
    },
    mounted() {
        this.initChart();
        window.addEventListener('resize', this.onWindowResize);
    },
    beforeDestroy() {
        if (this.chartInstance) {
            this.chartInstance.dispose();
        }
        window.removeEventListener('resize', this.onWindowResize);
    },
    methods: {
        initChart() {
            this.chartInstance = this.$echarts.getInstanceByDom(this.$refs.chart);
            if (!this.chartInstance) {
                this.chartInstance = this.$echarts.init(this.$refs.chart);
            }
            this.updateChart();
            this.chartInstance.on('click', this.handleChartClick);
            this.hasGeoroam && this.chartInstance.on('georoam', this.handleChartGeoroamClick);
        },
        updateChart() {
            this.chartInstance.setOption({
                ...this.options
            });
            this.chartInstance.resize();
        },
        handleChartClick(param) {
            const index = param.dataIndex;
            this.$emit('bar-clicked', param, this.chartInstance);
        },
        handleChartGeoroamClick(param) {
            this.$emit('georoam', param, this.chartInstance);
        },
        onWindowResize() {
            if (this.chartInstance) {
                this.chartInstance.resize();
            }
        },
        getChart(){
            return this.chartInstance
        }
    }
};
</script>
  
<style scoped>
.responsive-bar-chart {
    position: relative;
    width: 100%;
    height: 100%;
}
</style>